package com.example.projectdemo.mapper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.projectdemo.config.DBOpenHelper;
import com.example.projectdemo.domain.User;

import java.util.ArrayList;

public class UserMapper {


    private DBOpenHelper helper;
    private SQLiteDatabase db;
    private static final String TABLE_NAME = "User";

    public UserMapper(Context context) {
        helper = new DBOpenHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        //db = helper.getWritableDatabase();
    }

    /**
     * 插入数据
     * 用户注册
     * @param user
     */
    public void insert(User user) {
        db = helper.getWritableDatabase();// 以读写方法打开数据库，不仅仅是写，getReadableDatabase()是只读
        String sql = "insert into "+ TABLE_NAME +" (username,password,isDel) values (?,?,0)";
        // 传递过来的username与password分别按顺序替换上面sql语句的两个?，自动转换类型，下同，不再赘述
        String username = user.getName();
        String password = user.getPassword();
        Object bindArgs[] = new Object[] { username, password };
        // 执行这条无返回值的sql语句
        db.execSQL(sql, bindArgs);

    }

    /**
     * 查询所有
     *
     * @return
     */
    @SuppressLint("Range")
    public ArrayList<User> dbQueryAll() {
        db = helper.getWritableDatabase();
        ArrayList<User> userArrayList = new ArrayList<>();

        String sql = "select * from " + TABLE_NAME + " where isDel=0";
        Cursor cursor = db.rawQuery(sql, null);
        // 游标从头读到尾
        for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
            if (cursor.getInt(cursor.getColumnIndex("isDel")) != 1) {
                User user = new User();
                user.setName(cursor.getString(cursor
                        .getColumnIndex("username")));
                user.setPassword(cursor.getString(cursor
                        .getColumnIndex("password")));
                userArrayList.add(user);
            }
        }
        return userArrayList;
    }

    // 删除用户，其实是把相应的isDel值从0改1
    public void dbDeleteUser(int id) {
        db = helper.getWritableDatabase();
        String sql = "update " + TABLE_NAME + " set isDel=1 where id=?";
        Object bindArgs[] = new Object[]{id};
        db.execSQL(sql, bindArgs);
    }

    // 根据用户名，修改密码
    public void dbUpdatePassword(String username, String newPassword) {
        db = helper.getWritableDatabase();
        String sql = "update " + TABLE_NAME + " set password=? where username=? and isDel=0";
        Object bindArgs[] = new Object[]{newPassword, username};
        db.execSQL(sql, bindArgs);
    }


    public void closeDB() {
        db.close();
    }
}
